<?php
namespace interface\v1;
/*
*补卡接口类
*/
class workSignAddAppClass extends index
{
    private const table = 'work_sign_add';
    private const page = 'workSignAdd';
    private const title = '补卡申请';

    /*查询条件*/
    public function search()
    {
        //状态
        $data['result']['stateOption'] = array("草稿", "审核中", "已通过");
        $data['result']['timeOption'] = $this->timeOption;
        //返回
        $this->code = 1;
        $this->resp['data'] = $data;
    }

    /*列表页*/
    public function list()
    {
        //全等查询数组
        $equal = array(
            "stid" => self::$stid,//员工
            "state" => $this->post('state'),//审批状态
        );
        //初始化
        $and ='';
        if ($this->post('keyword')) {
            $and .= " and (text like '%".$this->post('keyword')."%' or orderNo like '%".$this->post('keyword')."%')";
        }

        $commitTime = $this->post('commit_time');
        if (!$commitTime) {
            if ($this->post('startDate')) {
                $commitTime = $this->post('startDate');
            }
            if ($this->post('endDate')) {
                $commitTime .= empty($commitTime) ? $this->post('endDate') : ('~' . $this->post('endDate'));
            }
        }
        if ($commitTime) {
            $and .= $this->miniTimeComparison($commitTime);
        }
        //获取查询结果
        $where = search(array("=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => "signTime desc"));
        //数据分析
        $data['result'] = [];
        foreach ($page['array'] as $array) {
            $staff = query("staff", "stid = '$array[stid]'");
            $data['result'][] = array(
                "id" => $array['id'],//补卡ID
                'orderNo'=>$array['orderNo'],
                "staffName" => $staff['name'],//申请人
                "signTime" => $array['signTime'],//补卡时间
                "text" => $array['text'],//补卡事由
                "state" => $array['state'],//状态
                'time'=>date('m/d',strtotime($array['time']))
            );
        }
        $data['page'] = $page['para'];
        //返回
        $this->code = 1;
        $this->resp['data'] = $data;
    }

    /**
     * 编辑页面
     */
    public function editPage(){
        $id = $this->post('id');
        $info = query(self::table,"id = '$id'");
        $this->code=1;
        $data=[];
        if ($id && empty($info['id'])){
            $this->code = 0;
            $this->resp['warn'] = '未找到此补卡申请';
        }elseif(!empty($info['id'])){
            $data['result'] = [
                'id'=>$id,
                'signTime'=>$info['signTime'],
                'text'=>$info['text'],
            ];
        }
        $this->resp['data'] = $data;
    }


    /**
     *
     * 获取此月份最后一天的时间
     * @param $month
     * @return string
     */
    public function lastMonthTime($month): string
    {
        //月份总天数
        $dayTotal = date('t', strtotime($month));
        return  $month.'-'.$dayTotal.' 23:59:59';//当月最后一天时间
    }
    /**
     * 编辑
     */
    public function commitEdit(){
        $id = $this->post('id') ?: self::getId();
        //赋值
        $field = array(
            "signTime" => $this->post('signTime'),
            "text" => $this->post('text'),//备注
            "updateTime" => date("Y-m-d H:i:s"),//更新时间
        );
        //补卡时间的月份
        $month = date('Y-m',strtotime($field['signTime']));
        $endTime = $this->lastMonthTime($month);
        if ($month == date('Y-m')){
            $endTime = $this->time;
        }
        //考勤规则
        $clockRule = query('clock_rule', " member like '%".self::$stid."%' and state = '启用' and UNIX_TIMESTAMP(startTime) <=UNIX_TIMESTAMP('{$endTime}') order by startTime desc");
        //当月已提交补卡的次数
        $commitNum = self::total(['table'=>self::table,'where'=>"id !='$id'  and stid = '".self::$stid."' and date_format(signTime,'%Y-%m') = '$month'"]);
        $info = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $this->resp['warn'] = "权限不足";
        } elseif (empty($field['signTime'])) {
            $this->resp['warn'] = "请选择补卡时间";
        } elseif (empty($field['text'])) {
            $this->resp['warn'] = "请填写补卡事由";
        } elseif (self::total(['table'=>self::table, 'where'=>" and signTime = '$field[signTime]' and stid = '".self::$stid."' and id != '" . $id . "' "]) > 0) {
            $this->resp['warn'] = "你已有此时间的补卡申请";
        } elseif($clockRule['maxNum'] !=-1 && $commitNum >= $clockRule['maxNum']){
            $this->resp['warn'] = "您提交的补卡次数已满，不能再提交了";
        } elseif($clockRule['maxDay'] != -1 && strtotime("-{$clockRule['maxDay']} day",strtotime($this->date)) > strtotime($field['signTime'])){
            $this->resp['warn'] = "您提交的补卡时间超出了补卡时限";
        } elseif(!empty($info['id']) && $info['state'] !=='草稿'){
            $this->resp['warn'] = '此补卡单不是草稿状态，不能编辑';
        }elseif (empty($info['id'])) {
            $userNo = self::generateCode(self::page,[
                'prefix' =>'BKSQ' . date('Ymd'),
                'table' =>  self::table,
                'field' => 'orderNo',
                'where' => '',
            ],$field);
            $department = query('department', " id = '{$this->controlJob['departmentId']}'");
            $field = array_merge($field, array("id" => $id, 'orderNo' => $userNo,'state'=>'草稿','deptName' => $department['name'],'stid' => $this->control['stid'], "time" => date("Y-m-d H:i:s")));
            $this->resp['warn'] = static::insert(array("table" => self::table, "field" => $field));
        } else {
            $this->resp['warn'] = static::update(array("table" => self::table, "field" => $field, "where" => "id = '$info[id]'"));
        }
        if (in_array($this->resp['warn'], array("新增成功", "更新成功"))) {
            //添加日志
            $type = mb_substr($this->resp['warn'], 0, 2, 'utf-8');
            $text = $this->control['name'] . $type . "了".self::title."ID：" .$id;
            $this->logText(array("type" => self::page, "text" => $text));
            $this->resp['data']['id'] = $id;
            //返回
            $this->code = 1;
        }

    }

    /*详情页*/
    public function detail()
    {
        $id = $this->post('id');
        $workSignAdd = query(self::table, "id = '" . $id . "'");
        if (empty($id)) {
            $this->resp['warn'] = "补卡ID为空";
        } elseif (empty($workSignAdd['id'])) {
            $this->resp['warn'] = "未找到此补卡记录";
        } else {
            //申请人
            $staff = query("staff", "stid = '$workSignAdd[stid]'");
            $audit = query('audit',"targetId = '$workSignAdd[id]' and flowName = '补卡申请'");
            $record = auditAppClass::auditRecord(self::table,$id);
            $auditRecord = [];
            $active = 0;
            if ($record !==false){
                $auditRecord = $record['record'];
                $active = $record['active'];
            }
            $data['result'] = [
                'id'=>$id,
                'flowName'=>'补卡申请',
                'staffName'=>$staff['name'],
                'ico'=>self::fillSrc($this->control['ico'],$this->control['updateTime']),
                'orderNo'=>$workSignAdd['orderNo'],
                'text'=>$workSignAdd['text'],
                'signTime'=>$workSignAdd['signTime'],
                'commitTime'=>$audit['commitTime'],
                'deptName'=>$workSignAdd['deptName'],
                'state'=>$workSignAdd['state'],
                'stid'=>$workSignAdd['stid'],
                'role'=>auditAppClass::role(self::table,$id),
                'auditRecord'=>$auditRecord,
                'active'=>$active,
            ];

            //返回
            $this->code = 1;
            $this->resp['data'] = $data;
        }
    }

    /**
     *
     * 提交审批前的验证
     */
    public function prepare($data): bool
    {
        $bool = true;
        $info = query(self::table," id = '$data[id]'");
        //判断提交次数是否超过了考勤规则的次数
        //补卡时间的月份
        $month = date('Y-m',strtotime($info['signTime']));
        $endTime = $this->lastMonthTime($month);//为什么找签到时间的当月月末时间 是当补卡为下个月的时候考虑的,如果是当月，则按当前时间来找规则
        if ($month == date('Y-m')){
            $endTime = $this->time;
        }
        //考勤规则
        $clockRule = query('clock_rule', " member like '%{$this->control['stid']}%' and state = '启用' and UNIX_TIMESTAMP(startTime) <=UNIX_TIMESTAMP('{$endTime}') order by startTime desc");
        //当月已提交补卡的次数
        $commitNum = self::total(['table'=>self::table,'where'=>" and stid = '{$this->control['stid']}' and state !='草稿' and date_format('{$info['signTime']}','%Y-%m') = '$month'"]);
        if($clockRule['maxNum'] !=-1 && $commitNum >= $clockRule['maxNum']){
            $bool = "您提交的补卡次数已满，不能再提交了";
        }
        return $bool;
    }
    /**
     * 审批结束后需要执行的操作
     * @param $data
     */
    public function finish($data){

        $this->insertSign($data['id']);//向签到记录表中插入一条数据
    }
    /**
     * 审核通过后向签到记录中添加一条记录
     */
    public function insertSign($id){

        $info = query('work_sign_add'," id = '$id'");
        $staff = query('staff'," stid = '$info[stid]'");
        $warn = insert(array(
            'table'=>'work_sign',
            'field'=>[
                'jobId'=>$staff['jobId'],
                'stid'=>$staff['stid'],
                'signTime'=>$info['signTime'],
                'signId'=>$info['id'],
                'type'=>'补卡单'
            ]
        ));

    }
    /**
     * 撤销审批后的
     * @param $data
     */
    public function cancelFun($data): string
    {
        //删除签到记录表中的补卡数据
       return delete(array('table'=>'work_sign', 'where'=>"signId = '$data[id]'"));
    }
    /**
     * 删除
     */
    public function delete()
    {
        $id = $this->post('id');
        $info = query(self::table, "id = '$id'");
        if (!$this->power(self::page, 'del')) {
            $this->resp['warn'] = "你没有删除的权限";
        } elseif (empty($info['id'])) {
            $this->resp['warn'] = "未找到此".self::title;
        } elseif ($info['stid'] != self::$stid) {
            $this->resp['warn'] = "这不是你的".self::title;
        } elseif ($info['state'] != '草稿') {
            $this->resp['warn'] = "此".self::title."不是草稿状态，不能删除";
        } else {
            $warn = delete(array('table' => self::table, 'where' => "id = '$id'"));
            if ($warn == '删除成功') {
                //删除audit表记录
                delete(array('table'=>'audit','where'=>"targetId = '$id'"));
                //删除待办事项
                delete(array("table" => "backlog","where" => " typeId = '$id' "));
                //删除审批记录
                delete(array("table" => "auditing_follow","where" => " typeId = '$id' "));
                //删除消息提醒
                delete(array("table" => "message","where" => " typeid = '$id' "));
                //添加记录
                $text = "{$this->control['name']}删除了一条" . self::title . "：ID【{$id}】" . '<br>';
                // 写入日志
                $this->logText(["type" => self::page, "text" => $text]);
                $this->code = 1;
                $this->resp['warn'] = '删除成功';
            } else {
                $this->resp['warn'] = '删除失败';
            }
        }
        resp:
    }
}
